/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.share.transport.http;

import java.nio.ByteBuffer;

import org.creativor.rayson.server.transport.http.ServerHttpRequest;

/**
 * An parser used to parse HTTP request message.
 * 
 * @author creativor
 */
public class HttpRequestParser extends HttpMessageParser<ServerHttpRequest> {

	public HttpRequestParser(final ByteBuffer byteBuffer) {
		super(byteBuffer);
	}

	@Override
	ServerHttpRequest newMessage() {
		return new ServerHttpRequest(new ExtendedHttpHeaders());
	}

	@Override
	public HttpRequestLine parseStartLine(final byte[] line)
			throws HttpProtocolException {

		final byte key = HttpConstants.SPACE;
		int pos = 0;
		int index = search(line, pos, key);
		if (index < 0)
			throw new HttpProtocolException("Request line format is wrong");
		final String methodStr = new String(copy(line, pos, index));

		HttpMethod method;
		try {
			method = HttpMethod.valueOf(methodStr);

		} catch (final Exception e) {

			throw new HttpProtocolException("Unsupported method " + methodStr);
		}

		pos = index + 1;
		index = search(line, pos, key);
		if (index < 0 || index >= line.length)
			throw new HttpProtocolException("Request line format is wrong");
		final String uri = new String(copy(line, pos, index));

		pos = index + 1;
		final String version = new String(copy(line, pos, line.length - 2));

		return new HttpRequestLine(method, uri.toString(), version.toString());

	}

}